﻿using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DotNetExtensions.AspNet.DevExpress.Services
{
    public interface IGridViewService
    {
        void Indicator<T>(GridControl gridControl);
        void Indicator(BaseView gridView, int count);
    }

    public class GridViewService : IGridViewService
    {
        public void Indicator(BaseView view, int count = 10)
        {
            if (view is GridView)
            {
                ((GridView)view).CustomDrawRowIndicator += (sender, e) =>
                {
                    if (e.Info.IsRowIndicator && e.RowHandle > -1)
                    {
                        e.Info.DisplayText = (e.RowHandle + 1).ToString();
                    }
                };

                ((GridView)view).IndicatorWidth = count.ToString().Length * 10 + 20;
            }
            else if (view is BandedGridView)
            {
                ((GridView)view).CustomDrawRowIndicator += (sender, e) =>
                {
                    if (e.Info.IsRowIndicator && e.RowHandle > -1)
                    {
                        e.Info.DisplayText = (e.RowHandle + 1).ToString();
                    }
                };

                ((GridView)view).IndicatorWidth = count.ToString().Length * 10 + 20;
            }
        }

        public void Indicator<T>(GridControl gridControl)
        {
            gridControl.DataSourceChanged += (sender, e) =>
            {
                if (gridControl.DataSource is IEnumerable<T>)
                {
                    int count = (gridControl.DataSource as IEnumerable<T>).Count();

                    Indicator(gridControl.MainView, count);
                }
            };
        }
    }
}
